import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;

import javax.swing.*;

@SuppressWarnings("serial")
public class ChatPanel extends JFrame implements WindowListener
{
        ChatArea chatArea;
        UserList users;
        CommandLine command;
        String username;
        GamePanel game;
        JScrollPane pane;
        ArrayList<String> IPs, ignored;
        
        public ChatPanel(String name)
        {
                username = name;
                setSize(700, 600);
                setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                addWindowListener(this);

                IPs = new ArrayList<String>();
                ignored = new ArrayList<String>();
                
                setLayout(new BorderLayout());
                JMenu file = new JMenu("File");
                JMenuItem logoff = new JMenuItem("Logoff");
                file.add(logoff);
                JMenuItem exit = new JMenuItem("Exit");
                file.add(exit);
                JMenuBar bar = new JMenuBar();
                bar.add(file);
                
                add(bar, BorderLayout.NORTH);
                
                chatArea = new ChatArea(this);
                users = new UserList(this);
                command = new CommandLine(this);
                add(command, BorderLayout.SOUTH);
                
                pane = new JScrollPane(chatArea);
                pane.setBorder(BorderFactory.createEmptyBorder());
                pane.getVerticalScrollBar().addAdjustmentListener(new AdjustmentListener() {

					@Override
					public void adjustmentValueChanged(AdjustmentEvent arg0) 
					{
			        	pane.getVerticalScrollBar().setValue(pane.getVerticalScrollBar().getMaximum());
					}
                	
                });
                
                game = new GamePanel(pane, this);
                
                JSplitPane split = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, game, users);
                split.setDividerLocation(550);
                split.setDividerSize(6);
                split.setResizeWeight(1);
                split.setContinuousLayout(true);
                
                JPanel panel = new JPanel(new BorderLayout());
                panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 0, 5));
                panel.add(split,BorderLayout.CENTER);
                add(panel, BorderLayout.CENTER);

                addWindowFocusListener(new WindowAdapter() {
                    public void windowGainedFocus(WindowEvent e) {
                        command.commandText.requestFocusInWindow();
                    }
                });
                setVisible(true);
        }


        public String[] getUserList() { 
                String[] ret;
                ret = IPs.toArray(new String[IPs.size()]);
                return ret;
        }
        
        private void displayWelcomeMessage() 
        {
                chatArea.welcomeMessage();
                chatArea.listUsers(users);
        }
        
        public void addIP(String IP, String username) { 
                IPs.add(username + ":" + IP.replace("/", ""));
                receiveLogin(username);
        }
        
        public void addIP(String IP) { 
                IPs.add(IP.replace("/", ""));
                receiveLogin(IP.split(":")[0]);
        }

        public void addUser(String name)
        {
                users.addUser(name);
                users.repaint();
        }
        
        public void receiveLogin(String name)
        {
                chatArea.login(name);
                users.addUser(name);
        }
        
        public void receiveLogoff(String name)
        {
                chatArea.logoff(name);
                users.removeUser(name);
                IPs.remove(getIndex(name));
        }
        
        public void receivePoke(String name)
        {
                if(!ignored.contains(name))
                        chatArea.poked(name);
        }
        
        public void receiveMessage(String name, String text)
        {
                if(!ignored.contains(name))
                        chatArea.addText(name,text);
        }

        public void receiveWhisper(String name, String text) 
        {
                if(!ignored.contains(name))
                        chatArea.addWhisper(name, text);
        }


		public void receiveEndedGame(int id, String username) 
		{
			chatArea.addSystemText(username + " has ended your game.");
			game.endGame(id);
		}
        
        public void sendIgnore(String name)
        {
                ignored.add(name);
                chatArea.ignore(name);
        }
        
        public void cancelIgnore(String name)
        {
                ignored.remove(name);
                chatArea.listen(name);
        }
        
        public void sendPoke(String name)
        {
                chatArea.poke(name);
                sendData(3, username, null, getIP(name));
        }
        
        public void interpret(String text) { 
    		String[] instruct = text.split(" ");
    		String direct = instruct[0];
    		direct = direct.substring(1, direct.length());
    		String user = instruct[1];
    		
    		if(direct.equals("w") || direct.equals("whisper")) {
    			text = text.replaceFirst(instruct[0] + " "  + instruct[1], "");
    			whisper(user, text);
    		} else if(direct.equals("ignore")) { 
    			sendIgnore(user);
    		} else if(direct.equals("listen")) { 
    			cancelIgnore(user);
    		}
    		else if(direct.equals("poke")) { 
    			sendPoke(user);
    		}
        }
        
        public void sendMessage(String text)
        {
        	if(text.charAt(0) == ('/')) { 
        		interpret(text);
        	} else {
                chatArea.addText(username,text);
                sendData(4,username,text);
        	}
        }

        public void sendWhisper(String name) 
        {
                String text = JOptionPane.showInputDialog(this, "Whisper to " + name + ":", "");
                if(text != null && text.length() > 0)
                	whisper(name, text);
        }
        
        public void whisper(String name, String text) { 
            chatArea.sendWhisper(name, text);
            sendData(5, username, text, getIP(name));
        }
        
        public String getIP(String name)
        {
                return IPs.get(getIndex(name)).split(":")[1];
        }
        
        public int getIndex(String name)
        {
                for(int i = 0; i < IPs.size(); i++)
                {
                        if(IPs.get(i).startsWith(name))
                                return i;
                }
                System.out.println("ERROR: Could not find \"" + name + "\"\'s IP Address");
                return -1;
        }
        
        public boolean isIgnoring(String name)
        {
                return ignored.contains(name);
        }
        
        public void listUsers()
        {
                chatArea.listUsers(users);
        }
        
        public void sendData(int type, String name, String msg)
        {
                String[] clientIPs = getUserList();
                for(int i = 0; i < clientIPs.length; i++) { 
                        sendData(type,  name,  msg, clientIPs[i].split(":")[1]);
                }
                
        }
        
        public void sendData(int type, String name, String msg, String IP)
        {
                Talker talker = new Talker(type, name, msg, IP);
                talker.start();
        }


        @Override
        public void windowClosing(WindowEvent arg0) 
        {
                sendData(2, username, null);
        }

        @Override
        public void windowDeactivated(WindowEvent arg0) {}
        @Override
        public void windowDeiconified(WindowEvent arg0) {}
        @Override
        public void windowIconified(WindowEvent arg0) {}
        @Override
        public void windowOpened(WindowEvent arg0) {}
        @Override
        public void windowActivated(WindowEvent arg0) {}
        @Override
        public void windowClosed(WindowEvent arg0) {}
}
